<template>
  <div class="chart-container">
    <!-- 根据当前路由显示对应的图表 -->
    <template v-if="$route.path.includes('/visualization/bar-race')">
      <div class="header">
        <h1>热门景点访问量竞速</h1>
        <p>展示各景点访问量随时间的变化趋势</p>
      </div>
      <div class="controls">
        <button @click="togglePlay" class="control-btn">{{ isPlaying ? '暂停' : '播放' }}</button>
        <button @click="resetChart" class="control-btn">重置</button>
        <select v-model="playSpeed" class="speed-select">
          <option :value="1">正常速度</option>
          <option :value="0.5">慢速</option>
          <option :value="2">快速</option>
        </select>
      </div>
      <div ref="chartContainer" class="chart" style="width: 100%; height: 600px;"></div>
    </template>
    <template v-else>
      <div class="header">
        <h1>热门景点排名季度变化</h1>
        <p>展示各景点在不同季度的排名变化趋势</p>
      </div>
      <div class="filters">
        <button class="filter-btn" :class="{ active: filterType === 'all' }" @click="setFilter('all')">全部景点</button>
        <button class="filter-btn" :class="{ active: filterType === 'top5' }" @click="setFilter('top5')">前5名</button>
        <button class="filter-btn" :class="{ active: filterType === 'popular' }" @click="setFilter('popular')">热门景点</button>
      </div>
      <div ref="chartContainer" class="chart" style="width: 100%; height: 600px;"></div>
      <div class="legend">
        <div v-for="(spot, index) in filteredSpots" :key="spot.name" 
             class="legend-item" :class="{ disabled: hiddenSeries.has(spot.name) }"
             @click="toggleSeries(spot.name)">
          <div class="legend-color" :style="{ backgroundColor: colors[index % colors.length] }"></div>
          <span class="legend-name">{{ spot.name }}</span>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
// 引入ECharts库
import * as echarts from 'echarts'

export default {
  name: 'HtmlViewer',
  data() {
    return {
      chart: null,
      // 排名波动图相关数据
      quarters: ['2023Q1', '2023Q2', '2023Q3', '2023Q4', '2024Q1', '2024Q2'],
      quartersText: ['2023年第一季度', '2023年第二季度', '2023年第三季度', 
                    '2023年第四季度', '2024年第一季度', '2024年第二季度'],
      spots: [],
      bumpData: {},
      filterType: 'all',
      filteredSpots: [],
      hiddenSeries: new Set(),
      // 条形图竞速相关数据
      timePoints: ['2023-01', '2023-02', '2023-03', '2023-04', '2023-05', '2023-06', 
                   '2023-07', '2023-08', '2023-09', '2023-10', '2023-11', '2023-12'],
      barRaceData: {},
      currentTimeIndex: 0,
      isPlaying: false,
      playTimer: null,
      playSpeed: 1,
      // 颜色配置
      colors: [
        '#FF6B6B', '#4ECDC4', '#45B7D1', '#F9CA24', '#6C5CE7',
        '#A29BFE', '#FD79A8', '#FDCB6E', '#00B894', '#E17055'
      ]
    };
  },
  mounted() {
    // 确保DOM已渲染
    this.$nextTick(() => {
      this.initData()
      this.initChart()
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
    this.stopPlay()
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    // 初始化数据
    initData() {
      // 初始化景点数据
      this.spots = [
        { name: '长城', baseRank: 1, volatility: 0.2, baseVisitors: 850000 },
        { name: '故宫博物院', baseRank: 2, volatility: 0.3, baseVisitors: 780000 },
        { name: '西湖', baseRank: 3, volatility: 0.4, baseVisitors: 720000 },
        { name: '颐和园', baseRank: 4, volatility: 0.35, baseVisitors: 680000 },
        { name: '黄山风景区', baseRank: 5, volatility: 0.5, baseVisitors: 650000 },
        { name: '兵马俑', baseRank: 6, volatility: 0.25, baseVisitors: 620000 },
        { name: '天坛公园', baseRank: 7, volatility: 0.3, baseVisitors: 580000 },
        { name: '九寨沟', baseRank: 8, volatility: 0.6, baseVisitors: 550000 },
        { name: '张家界', baseRank: 9, volatility: 0.55, baseVisitors: 530000 },
        { name: '布达拉宫', baseRank: 10, volatility: 0.45, baseVisitors: 500000 }
      ]
      
      // 根据路由初始化对应的数据
      if (this.$route.path.includes('/visualization/bar-race')) {
        this.initBarRaceData()
      } else {
        this.initBumpData()
      }
    },
    
    // 初始化条形图竞速数据
    initBarRaceData() {
      // 生成每个景点的月度访问量数据
      this.spots.forEach(spot => {
        this.barRaceData[spot.name] = []
        let currentVisitors = spot.baseVisitors
        
        this.timePoints.forEach((timePoint, index) => {
          // 月度波动逻辑（添加季节性因素）
          let seasonalFactor = 1
          // 春节期间（2月）
          if (index === 1) {
            seasonalFactor = 1.5
          }
          // 五一、十一假期
          if (index === 4 || index === 9) {
            seasonalFactor = 1.4
          }
          // 暑假（7-8月）
          if (index === 6 || index === 7) {
            seasonalFactor = 1.3
          }
          // 淡季
          if (index === 0 || index === 2 || index === 10 || index === 11) {
            seasonalFactor = 0.85
          }
          
          // 添加随机波动
          const randomFactor = 0.8 + Math.random() * 0.4
          currentVisitors = Math.max(0, spot.baseVisitors * seasonalFactor * randomFactor)
          this.barRaceData[spot.name].push(Math.round(currentVisitors))
        })
      })
    },
    
    // 初始化排名波动图数据
    initBumpData() {
      // 生成每个景点的季度排名数据
      this.spots.forEach(spot => {
        this.bumpData[spot.name] = []
        let currentRank = spot.baseRank
        
        this.quarters.forEach((quarter, index) => {
          // 排名波动逻辑
          const change = Math.floor((Math.random() - 0.5) * 2 * spot.volatility * 4)
          currentRank = Math.max(1, Math.min(10, currentRank + change))
          
          // 季度性调整
          let seasonalAdjustment = 0
          if (spot.name === '九寨沟' || spot.name === '张家界') {
            // 夏季旅游景点在Q2/Q3表现更好
            if (index === 1 || index === 2 || index === 4 || index === 5) {
              seasonalAdjustment = -1
            }
          } else if (spot.name === '长城' || spot.name === '颐和园') {
            // 春秋季节更适合
            if (index === 0 || index === 2 || index === 3 || index === 5) {
              seasonalAdjustment = -1
            }
          }
          
          currentRank = Math.max(1, Math.min(10, currentRank + seasonalAdjustment))
          this.bumpData[spot.name].push(currentRank)
        })
      })
    },
    
    // 初始化图表
    initChart() {
      // 检查容器是否存在
      if (!this.$refs.chartContainer) {
        console.error('图表容器不存在')
        return
      }
      
      // 初始化ECharts实例
      this.chart = echarts.init(this.$refs.chartContainer)
      
      // 根据路由初始化对应的图表
      if (this.$route.path.includes('/visualization/bar-race')) {
        this.updateBarRaceChart()
      } else {
        // 初始化排名波动图的筛选
        this.setFilter('all')
        this.updateBumpChart()
      }
    },
    
    // 更新条形图竞速图表
    updateBarRaceChart() {
      const currentTime = this.timePoints[this.currentTimeIndex]
      
      // 准备当前时间点的数据
      const chartData = []
      this.spots.forEach((spot, index) => {
        chartData.push({
          name: spot.name,
          value: this.barRaceData[spot.name][this.currentTimeIndex],
          itemStyle: {
            color: this.colors[index % this.colors.length]
          }
        })
      })
      
      // 按访问量排序
      chartData.sort((a, b) => b.value - a.value)
      
      const option = {
        title: {
          text: `景点访问量排名 - ${currentTime}`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            const data = params[0]
            return `${data.name}<br/>访问量: ${data.value.toLocaleString()}`
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLabel: {
            formatter: (value) => {
              if (value >= 10000) {
                return (value / 10000).toFixed(1) + '万'
              }
              return value
            }
          }
        },
        yAxis: {
          type: 'category',
          data: chartData.map(item => item.name).reverse(),
          axisLabel: {
            interval: 0
          }
        },
        series: [{
          type: 'bar',
          data: chartData.map(item => ({
            value: item.value,
            itemStyle: item.itemStyle,
            label: {
              show: true,
              position: 'right',
              formatter: (params) => params.value.toLocaleString()
            }
          })).reverse(),
          barWidth: '60%'
        }]
      }
      
      this.chart.setOption(option, true)
    },
    
    // 切换播放状态
    togglePlay() {
      if (this.isPlaying) {
        this.stopPlay()
      } else {
        this.startPlay()
      }
    },
    
    // 开始播放
    startPlay() {
      this.isPlaying = true
      this.playTimer = setInterval(() => {
        this.currentTimeIndex++
        if (this.currentTimeIndex >= this.timePoints.length) {
          this.currentTimeIndex = 0
        }
        this.updateBarRaceChart()
      }, 1000 / this.playSpeed)
    },
    
    // 停止播放
    stopPlay() {
      this.isPlaying = false
      if (this.playTimer) {
        clearInterval(this.playTimer)
        this.playTimer = null
      }
    },
    
    // 重置图表
    resetChart() {
      this.stopPlay()
      this.currentTimeIndex = 0
      this.updateBarRaceChart()
    },
    
    // 设置筛选条件
    setFilter(type) {
      this.filterType = type
      
      if (type === 'all') {
        this.filteredSpots = [...this.spots]
      } else if (type === 'top5') {
        this.filteredSpots = this.spots.slice(0, 5)
      } else if (type === 'popular') {
        this.filteredSpots = this.spots.filter(spot => spot.baseRank <= 7)
      }
      
      this.updateBumpChart()
    },
    
    // 切换系列显示/隐藏
    toggleSeries(seriesName) {
      if (this.hiddenSeries.has(seriesName)) {
        this.hiddenSeries.delete(seriesName)
      } else {
        this.hiddenSeries.add(seriesName)
      }
      this.updateBumpChart()
    },
    
    // 更新排名波动图
    updateBumpChart() {
      const series = []
      
      this.filteredSpots.forEach((spot, index) => {
        if (!this.hiddenSeries.has(spot.name)) {
          series.push({
            name: spot.name,
            type: 'line',
            data: this.bumpData[spot.name],
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 3,
              color: this.colors[index % this.colors.length]
            },
            itemStyle: {
              color: this.colors[index % this.colors.length],
              borderWidth: 2,
              borderColor: '#fff'
            },
            emphasis: {
              focus: 'series',
              itemStyle: {
                symbolSize: 12
              }
            },
            tooltip: {
              formatter: (params) => {
                const quarter = this.quartersText[params.dataIndex]
                return `${params.name}<br/>${quarter}<br/>排名: ${params.value}`
              }
            }
          })
        }
      })
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          show: false
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.quartersText,
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          min: 1,
          max: 10,
          interval: 1,
          inverse: true, // 反转Y轴，使排名1在顶部
          axisLabel: {
            formatter: '{value} 名'
          }
        },
        series: series
      }
      
      this.chart.setOption(option, true)
    },
    
    // 处理窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  }
}
</script>

<style scoped>
.chart-container {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.header h1 {
  color: #333;
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 600;
}

.header p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

/* 条形图竞速控制按钮样式 */
.controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.control-btn {
  padding: 10px 20px;
  border: none;
  background: #409eff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  font-weight: 500;
}

.control-btn:hover {
  background: #66b1ff;
  transform: translateY(-1px);
}

.control-btn:active {
  background: #3a8ee6;
  transform: translateY(0);
}

.speed-select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  background: white;
  min-width: 120px;
  transition: border-color 0.3s;
}

.speed-select:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

/* 排名波动图筛选按钮样式 */
.filters {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-btn {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.filter-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

.filter-btn.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.chart {
  margin-bottom: 20px;
  min-height: 600px;
}

/* 图例样式 */
.legend {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: opacity 0.3s;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.legend-item:hover {
  opacity: 0.8;
  background: #f5f7fa;
}

.legend-item.disabled {
  opacity: 0.4;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 3px;
  margin-right: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.legend-name {
  font-size: 14px;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-container {
    padding: 10px;
  }
  
  .header h1 {
    font-size: 20px;
  }
  
  .controls {
    flex-direction: column;
    gap: 10px;
  }
  
  .control-btn {
    width: 200px;
  }
  
  .speed-select {
    width: 200px;
  }
  
  .filters {
    gap: 8px;
  }
  
  .filter-btn {
    padding: 6px 12px;
    font-size: 12px;
  }
  
  .legend {
    gap: 10px;
  }
  
  .legend-item {
    font-size: 12px;
  }
  
  .chart {
    min-height: 400px;
  }
}
</style>